import { ListNode } from "./utils";

export function mergeTwoLists(l1: ListNode | null, l2: ListNode | null): ListNode | null {

    const dummyHead = new ListNode();
    let curL1 = l1;
    let curL2 = l2;
    let cur = dummyHead;

    // 为了不影响原链表的关系，可以复制其中的值，创建新的链表结点
    while (curL1 && curL2) {
        if (curL1.val < curL2.val) {
            cur.next = new ListNode(curL1.val);
            curL1 = curL1.next;
        } else {
            cur.next = new ListNode(curL2.val);
            curL2 = curL2.next;
        }
        cur = cur.next;
    }

    const copy = function (l: ListNode | null, cur: ListNode) {
        if (!l) return;
        while (l) {
            cur.next = new ListNode(l.val);
            cur = cur.next;
            l = l.next;
        }
    }
    copy(curL1, cur);
    copy(curL2, cur);

    return dummyHead.next;
};